package com.codemes.happylist.modules.pdf.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.codemes.happylist.utils.DocumentUtil;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;
import com.itextpdf.styledxmlparser.jsoup.Jsoup;
import com.itextpdf.styledxmlparser.jsoup.nodes.Document;
import com.itextpdf.styledxmlparser.jsoup.select.Elements;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author nscoffee
 */
@Slf4j
@Service
public class PdfCreateServiceImpl implements PdfCreateService{

    @Override
    public File genPdfWithSingleWebLink(String destDir, String destFileName, String link, String contentTagName) {
        link = URLUtil.decode(link);
        try {
            return HtmlToPdfUtil.htmlToPdf(link,destDir,contentTagName,destFileName);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public File genPdfWithCatalogLink(String destDir, String destFileName, String catalogLink, String contentTagInfo) throws IOException {

        catalogLink = URLUtil.decode(catalogLink);
        // 提取连接
        List<String> allUrls = new ArrayList<>();
        allUrls.add(URLUtil.decode(catalogLink));

        String urlBase = getUrlBasePath(URLUtil.url(catalogLink));
        String content = HttpUtil.get(catalogLink);
        Document document = Jsoup.parse(content,"utf-8");
        Elements element = document.getElementsByClass(contentTagInfo);
        Elements allLinks = element.select("a");
        allLinks.forEach(link -> {
            String absHref = link.attr("href");
            log.info(urlBase+absHref);
            allUrls.add(URLUtil.decode(urlBase+absHref));
        });

        List<File> files = new ArrayList<>();
        String tmpDir = destDir+File.separator+IdUtil.fastUUID();
        allUrls.forEach((url) -> {
            try {
                File file = HtmlToPdfUtil.htmlToPdf(url,tmpDir,contentTagInfo);
                files.add(file);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        files.sort((o1, o2) -> (int)(o1.lastModified()-o2.lastModified()));

        File dest = new File(destDir,  destFileName);
        doMergePdf(files,dest);
        FileUtil.del(tmpDir);
        return dest;
    }

    private void doMergePdf(List<File> pdfList, File dest){
        try (PdfDocument first = new PdfDocument(new PdfWriter(dest))){
            PdfMerger pdfMerger = new PdfMerger(first);
            doMergePdf(pdfList, pdfMerger);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doMergePdf(List<File> pdfList, PdfMerger pdfMerger) {
        for (File pdf: pdfList) {
            try (PdfDocument second = new PdfDocument(new PdfReader(pdf))){
                pdfMerger.merge(second,1,second.getNumberOfPages());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String getUrlBasePath(URL url) {
        if(url.getPort()>0){
            return url.getProtocol()+"://"+ url.getHost()+":"+ url.getPort();
        }
        return url.getProtocol()+"://"+ url.getHost();
    }


}
